package org.lyfeng.spring.core.support;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.lyfeng.spring.core.io.Resource;

/**
 * @author leiyufeng
 * 2013-4-24 下午8:53:46
 */
public class ResourceLoader implements Resource{
	private String path;    // "org/test/lyfeng/Test.class"
	private ClassLoader classLoader;
	private Class<?> clazz;
	public ResourceLoader() {
		// TODO Auto-generated constructor stub
	}
	public ResourceLoader(String path,ClassLoader classLoader)
	{
		this.path=path;
		this.classLoader=classLoader;
	}
	public ResourceLoader(Class<?> clazz,String path)
	{
		this.clazz=clazz;
		this.path=path;
		this.classLoader=clazz.getClassLoader();
	}
	@Override
	public File getFile() throws IOException {
		// TODO Auto-generated method stub
		File file=new File(this.path);
		if(file.exists())
			return file;
		else
			throw new FileNotFoundException(this.path+"找不到");
	}

	@Override
	public String getFilename() {
		// TODO Auto-generated method stub
		File file=new File(this.path);
		return file.getName();
	}

	@Override
	public InputStream getInputStream() throws IOException {
		// TODO Auto-generated method stub
		InputStream is=this.classLoader.getResourceAsStream(this.path);
		if(null==is)
		{
			throw new FileNotFoundException(this.path+" 找不到");
		}
		return is;
	}
	@Override
	public URL getURL() throws IOException {
		// TODO Auto-generated method stub
		URL url;
		if(this.clazz!=null)
		{
			url=this.clazz.getResource(this.path);
		}else{
			url=this.classLoader.getResource(this.path);
		}
		if(url==null)
		{
			throw new FileNotFoundException(this.path+" 找不到");
		}
		return url;
	}
	
}
